package com.sx.baseproject.framework.net.base;


import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;

import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.security.auth.login.LoginException;

import io.reactivex.ObservableEmitter;

import io.reactivex.ObservableEmitter;

import static com.lzy.okgo.cache.CacheMode.FIRST_CACHE_THEN_REQUEST;
import static com.lzy.okgo.cache.CacheMode.IF_NONE_CACHE_REQUEST;
import static com.lzy.okgo.cache.CacheMode.NO_CACHE;

public class ResponseCallBack<T> extends StringCallback {
    public ObservableEmitter emitter;
    Class mclass;
    public FileProgress fileProgress;
    public CacheMode cacheMode = NO_CACHE;
    public int count = 0;

    public ResponseCallBack(ObservableEmitter emitter, Class mclass, FileProgress fileProgress) {
        this.emitter = emitter;
        this.mclass = mclass;
        this.fileProgress = fileProgress;
    }


    public ResponseCallBack(ObservableEmitter emitter, Class mclass) {
        this.emitter = emitter;
        this.mclass = mclass;
    }

    public ResponseCallBack(ObservableEmitter emitter, Class mclass, CacheMode cacheMode) {
        this.emitter = emitter;
        this.mclass = mclass;
        this.cacheMode = cacheMode;
    }

    @Override
    public void onCacheSuccess(Response<String> response) {
        super.onCacheSuccess(response);
        onSuccess(response);
    }

    @Override
    public void onSuccess(Response<String> response) {
        count += 1;
        String body = response.body();
        if (!TextUtils.isEmpty(body)) {
            Log.i("ResponseCallBack", body);
            try {
                JSONObject jsonBody = new JSONObject(body);
//                int code = Integer.valueOf(jsonBody.getString("code"));
                String message = "noFindErrorInfo";
                if (!jsonBody.isNull("desc")) {
                    message = jsonBody.getString("desc");
                }
                if (!jsonBody.isNull("flag") && ("998".equals(jsonBody.getString("flag"))|| "997".equals(jsonBody.getString("flag")))) {
                    emitter.tryOnError(new LoginException());
                    return;
                }
                boolean status = jsonBody.getBoolean("status");
                if (status) {
//                    switch (code) {
//                        case 1:
                    //请求成功
                    if (mclass == NullResponse.class) {
                        emitter.onNext(new NullResponse());
                    } else {
                        String data = jsonBody.getString("data");
                        if (!TextUtils.isEmpty(data)) {
                            if (jsonBody.get("data") instanceof org.json.JSONArray) {
                                emitter.onNext(new Gson().fromJson(data, new ParameterizedTypeImpl(mclass)));
                            } else if (mclass == String.class || mclass == Integer.class || mclass == Double.class || mclass == Float.class || mclass == Boolean.class) {
                                emitter.onNext(data);
                            } else {
                                emitter.onNext(new Gson().fromJson(data, mclass));

                            }
                        } else {
                            throw new NullPointerException(message);
                        }
                    }

                    if (cacheMode == NO_CACHE) {
                        emitter.onComplete();
                    } else if (cacheMode == FIRST_CACHE_THEN_REQUEST) {
                        if (count > 1) {
                            emitter.onComplete();
                        }
                    } else if (cacheMode == IF_NONE_CACHE_REQUEST) {
                        emitter.onComplete();
                    }
                } else {
                    throw new Exception(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
                emitter.tryOnError(e);
            }
        } else {
            //返回空
            emitter.tryOnError(new NullPointerException("数据出错"));
        }

    }

    @Override
    public void onError(Response<String> response) {
        super.onError(response);
        emitter.tryOnError(response.getException());
    }

    @Override
    public void uploadProgress(Progress progress) {
        if (fileProgress != null) {
            fileProgress.uploadProgress((int) progress.fraction * 100);
        }
    }

    @Override
    public void downloadProgress(Progress progress) {
        super.downloadProgress(progress);
        if (fileProgress != null) {
            fileProgress.downloadProgress((int) progress.fraction * 100);
        }
    }

    /**
     * 参数类型转换
     */
    private static class ParameterizedTypeImpl implements ParameterizedType {
        private Class clazz;

        public ParameterizedTypeImpl(Class clz) {
            clazz = clz;
        }

        public Type[] getActualTypeArguments() {
            return new Type[]{clazz};
        }

        public Type getRawType() {
            return List.class;
        }

        public Type getOwnerType() {
            return null;
        }
    }

    public static <T> List<T> jsonToBeanList(String json, Class<T> clas) {
        Gson gson = new Gson();
        List<T> list = gson.fromJson(json, new TypeToken<List<T>>() {
        }.getType());
        // 这个地方可以正常打印
        for (T t : list) {
            System.out.println(t);
        }
        return list;
    }


}
